<template>
  <div>
    <input type="file" placeholder="Select file..." @change="handleChange" />
    <pre>{{ result }}</pre>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import mediaInfoFactory from "mediainfo.js";

const result = ref(""); // 保存分析结果的文本
let mediaInfoRef = null; // 保存 MediaInfo 实例

// 在组件挂载时初始化 MediaInfo
onMounted(() => {
  mediaInfoFactory({ format: "text" })
    .then((mi) => {
      mediaInfoRef = mi;
    })
    .catch((error) => {
      console.error("Error initializing MediaInfo:", error);
    });
});

// 在组件卸载时清理 MediaInfo 实例
onUnmounted(() => {
  if (mediaInfoRef) {
    mediaInfoRef.close();
  }
});

// 读取文件块的函数
const makeReadChunk = (file) => {
  return async (chunkSize, offset) => {
    return new Uint8Array(
      await file.slice(offset, offset + chunkSize).arrayBuffer()
    );
  };
};

// 处理文件选择事件
const handleChange = (ev) => {
  const file = ev.target.files?.[0];
  if (file && mediaInfoRef) {
    // 使用 makeReadChunk 创建读取函数
    const readChunk = makeReadChunk(file);
    mediaInfoRef
      .analyzeData(file.size, readChunk)
      .then((analysisResult) => {
        result.value = analysisResult; // 使用分析输出更新 result
      })
      .catch((error) => {
        console.error("Error analyzing file:", error);
      });
  }
};
</script>
